package org.mm.proxycache.config;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.inject.Inject;

public class ConfigReader
{
    private static Logger log = LoggerFactory.getLogger( ConfigReader.class );

    Config config;

    @Inject
    public ConfigReader( Config config )
    {
        Properties props = new Properties();
        File confFile = new File( "alijo.conf" );
        try
        {
            props.load( new BufferedInputStream( new FileInputStream( confFile ) ) );
        } catch (FileNotFoundException e)
        {
            log.error( "Configuration file not found '{}'", confFile );
        } catch (IOException e)
        {
            log.error( "Error reading configuration file '{}': {}", confFile, e );
        }

        Class<? extends Config> clazz = config.getClass();
        for ( Field field : clazz.getFields() )
        {
            String name = translateName( field.getName() );
            Class<?> type = field.getType();
            try
            {

                if ( type.getName().equals( "int" ) )
                {
                    int value = Integer.parseInt( props.getProperty( name ) );
                    field.setInt( config, value );
                } else if ( type == String.class )
                {
                    field.set( config, props.getProperty( name ) );
                } else if ( type.getName().equals( "boolean" ) )
                {
                    boolean value = Boolean.parseBoolean( props.getProperty( name ) );
                    field.setBoolean( config, value );
                }

            } catch (IllegalAccessException e)
            {
                log.error( "Error: {}", e );
            }
        }

        for ( Field field : clazz.getFields() )
        {
            String name = translateName( field.getName() );

            try
            {
                log.debug( "{}: {}", name, field.get( config ) );
            } catch (IllegalAccessException e)
            {
                log.error( "Error: {}", e );
            }
        }

    }

    private static String translateName( String name )
    {
        StringBuilder sb = new StringBuilder();
        for ( char c : name.toCharArray() )
        {
            if ( Character.isLowerCase( c ) )
                sb.append( c );
            else
            {
                sb.append( '.' ).append( Character.toLowerCase( c ) );
            }
        }

        return sb.toString();
    }
}
